import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { LearningProgress, Achievement } from '@/types'

export const useProgressStore = defineStore('progress', () => {
  // 从localStorage加载进度数据
  const loadProgress = (): LearningProgress => {
    const saved = localStorage.getItem('poetry-learning-progress')
    if (saved) {
      try {
        return JSON.parse(saved)
      } catch (error) {
        console.error('Failed to parse progress data:', error)
      }
    }
    
    // 默认进度
    return {
      learned_poems: [],
      mastered_poems: [],
      favorites: [],
      current_streak: 0,
      last_learned_date: '',
      total_learn_time: 0
    }
  }
  
  const progress = ref<LearningProgress>(loadProgress())
  
  // 保存进度到localStorage
  const saveProgress = () => {
    localStorage.setItem('poetry-learning-progress', JSON.stringify(progress.value))
  }
  
  // 标记古诗为已学习
  const markPoemAsLearned = (poemId: number) => {
    if (!progress.value.learned_poems.includes(poemId)) {
      progress.value.learned_poems.push(poemId)
      progress.value.last_learned_date = new Date().toISOString().split('T')[0]
      
      // 检查是否增加连续学习天数
      const today = new Date().toISOString().split('T')[0]
      const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString().split('T')[0]
      
      if (progress.value.last_learned_date === today) {
        // 今天的第一次学习
        if (progress.value.last_learned_date !== yesterday) {
          // 昨天没有学习，重置连续天数
          progress.value.current_streak = 1
        } else {
          // 连续学习
          progress.value.current_streak += 1
        }
      }
      
      saveProgress()
    }
  }
  
  // 标记古诗为已掌握
  const markPoemAsMastered = (poemId: number) => {
    if (!progress.value.mastered_poems.includes(poemId)) {
      progress.value.mastered_poems.push(poemId)
      
      // 确保也在已学习列表中
      if (!progress.value.learned_poems.includes(poemId)) {
        progress.value.learned_poems.push(poemId)
      }
      
      saveProgress()
    }
  }
  
  // 切换收藏状态
  const toggleFavorite = (poemId: number) => {
    const index = progress.value.favorites.indexOf(poemId)
    if (index > -1) {
      progress.value.favorites.splice(index, 1)
    } else {
      progress.value.favorites.push(poemId)
    }
    saveProgress()
  }
  
  // 添加学习时间
  const addLearnTime = (minutes: number) => {
    progress.value.total_learn_time += minutes
    saveProgress()
  }
  
  // 计算学习进度百分比
  const getProgressPercentage = computed(() => {
    const total = 24 // 总共24首古诗
    return Math.round((progress.value.learned_poems.length / total) * 100)
  })
  
  // 计算掌握进度百分比
  const getMasteryPercentage = computed(() => {
    const total = 24
    return Math.round((progress.value.mastered_poems.length / total) * 100)
  })
  
  // 成就系统
  const achievements = ref<Achievement[]>([
    {
      id: 'beginner',
      name: '初学者',
      description: '学习5首古诗',
      icon: 'badge_star',
      unlocked: false,
      condition: { type: 'poems_learned', value: 5 }
    },
    {
      id: 'intermediate',
      name: '进阶学者',
      description: '学习10首古诗',
      icon: 'badge_star',
      unlocked: false,
      condition: { type: 'poems_learned', value: 10 }
    },
    {
      id: 'expert',
      name: '诗词达人',
      description: '学习15首古诗',
      icon: 'badge_trophy',
      unlocked: false,
      condition: { type: 'poems_learned', value: 15 }
    },
    {
      id: 'master',
      name: '背诵大师',
      description: '掌握10首古诗',
      icon: 'badge_trophy',
      unlocked: false,
      condition: { type: 'poems_mastered', value: 10 }
    },
    {
      id: 'collector',
      name: '收藏家',
      description: '收藏5首古诗',
      icon: 'icon_favorite',
      unlocked: false,
      condition: { type: 'favorites', value: 5 }
    },
    {
      id: 'streak_7',
      name: '坚持者',
      description: '连续学习7天',
      icon: 'badge_trophy',
      unlocked: false,
      condition: { type: 'streak', value: 7 }
    }
  ])
  
  // 检查并解锁成就
  const checkAchievements = () => {
    achievements.value.forEach(achievement => {
      if (achievement.unlocked) return
      
      let meetsCondition = false
      switch (achievement.condition.type) {
        case 'poems_learned':
          meetsCondition = progress.value.learned_poems.length >= achievement.condition.value
          break
        case 'poems_mastered':
          meetsCondition = progress.value.mastered_poems.length >= achievement.condition.value
          break
        case 'favorites':
          meetsCondition = progress.value.favorites.length >= achievement.condition.value
          break
        case 'streak':
          meetsCondition = progress.value.current_streak >= achievement.condition.value
          break
      }
      
      if (meetsCondition) {
        achievement.unlocked = true
        achievement.unlocked_date = new Date().toISOString().split('T')[0]
      }
    })
  }
  
  // 获取已解锁的成就
  const getUnlockedAchievements = computed(() => {
    return achievements.value.filter(a => a.unlocked)
  })
  
  // 获取锁定的成就
  const getLockedAchievements = computed(() => {
    return achievements.value.filter(a => !a.unlocked)
  })
  
  // 初始化时检查成就
  checkAchievements()
  
  return {
    progress,
    achievements,
    markPoemAsLearned,
    markPoemAsMastered,
    toggleFavorite,
    addLearnTime,
    getProgressPercentage,
    getMasteryPercentage,
    checkAchievements,
    getUnlockedAchievements,
    getLockedAchievements,
    saveProgress
  }
})